package com.eduplatform.common;

import com.eduplatform.entity.User;
import com.eduplatform.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户上下文工具类，用于获取当前登录用户信息
 */
@Component
public class UserContext {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 获取当前登录用户
     *
     * @return 当前登录用户，如果未登录则返回null
     */
    public User getCurrentUser() {
        // 获取当前请求
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return null;
        }

        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("Authorization");

        if (token == null || token.isEmpty()) {
            return null;
        }

        // 检查并提取token
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        // 检查token格式
        if (!token.contains(".") || token.split("\\.").length != 3) {
            return null;
        }

        String username = jwtUtils.extractUsername(token);
        if (username == null) {
            return null;
        }

        return userService.getUserByUsername(username);
    }

    /**
     * 获取当前登录用户ID
     *
     * @return 当前登录用户ID，如果未登录则返回null
     */
    public Long getCurrentUserId() {
        User user = getCurrentUser();
        return user != null ? user.getId() : null;
    }
} 